/**
 * Copyright (c) 2022 az13js
 * new_program & new_program_server is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of
 * the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF
 * ANY KIND,EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
#include <sys/types.h>
#include <unistd.h>
#include <fstream>
#include <string>

#include <iomanip>
#include <ctime>
#include <chrono>

void record_pid() {
    using namespace std;
    using std::chrono::system_clock;
    using std::chrono::milliseconds;
    using std::chrono::duration_cast;
    char f[15] = {'\0'};
    auto pid = getpid();
    sprintf(f, "%d.txt\0", pid);

    auto fileName = string("bin/") + string(f);

    ofstream file(fileName, ofstream::app);
    if (file.is_open()) {
        auto time_point_now = system_clock::now();
        auto now_sec = system_clock::to_time_t(time_point_now); // now_sec只能精确到秒
        auto time_point_sec = system_clock::from_time_t(now_sec);
        auto diff_time = time_point_now - time_point_sec; // diff_time>0, 精确的时间和now_sec之间的差距，不足1秒的部分
        file << std::put_time(std::localtime(&now_sec), "%FT%T.");
        file << std::setw(3) << std::setfill('0') << duration_cast<milliseconds>(diff_time).count();
        file << std::put_time(std::localtime(&now_sec), "%z");
        file << " [test_program] " << (int)pid;
        file << std::endl;
    }
}

int main(void) {
    record_pid();
    return 0;
}

